package com.sdau.soa.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;

@Configuration
@MapperScan("com.sdau.soa.dao")
@EnableTransactionManagement
@EnableAsync(proxyTargetClass=true)
public class MybatisConfig {
    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;



    /**
     * SqlSession工厂
     * @return
     * @throws PropertyVetoException
     * @throws IOException
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws PropertyVetoException, IOException {
        ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactoryBean =new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:mapping/*.xml"));
        return sqlSessionFactoryBean;
    }

    //事务管理器
//    @Bean(name="transactionManager")
//    public DataSourceTransactionManager dataSourceTransactionManager() throws PropertyVetoException {
//        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
//        dataSourceTransactionManager.setDataSource(dataSource);
//        return dataSourceTransactionManager;
//    }
    @Bean(name = "transactionManager")  //给事务管理器命名
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
